package com.fw.ui.view.common.util;

import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

import javax.imageio.ImageIO;

import com.vaadin.server.StreamResource.StreamSource;

public class ImageStreamSource implements StreamSource {

    /**
     * 
     */
    private static final long serialVersionUID = 1L;

    private byte[] bytes;

    public ImageStreamSource() {
	super();
    }

    public ImageStreamSource(byte[] bytes) {
	super();
	this.bytes = bytes;
    }

    /*
     * We need to implement this method that returns
     * the resource as a stream.
     */
    public InputStream getStream() {
	try {
	    BufferedImage img = ImageIO.read(new ByteArrayInputStream(bytes));

	    /* Write the image to a buffer. */
	    ByteArrayOutputStream imagebuffer = new ByteArrayOutputStream();
	    ImageIO.write(img, "png", imagebuffer);

	    /* Return a stream from the buffer. */
	    return new ByteArrayInputStream(imagebuffer.toByteArray());
	} catch (IOException e) {
	    return null;
	}
    }

    public byte[] getBytes() {
	return bytes;
    }

    public void setBytes(byte[] bytes) {
	this.bytes = bytes;
    }

}
